//
//  AddAddressViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/16.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "AddAddressViewController.h"
#import "AddressModel.h"

@interface AddAddressViewController () <UITextFieldDelegate, UIPickerViewDataSource,UIPickerViewDelegate>

@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *address;
@property (weak, nonatomic) IBOutlet UITextField *zipCode;
@property (weak, nonatomic) IBOutlet UITextView *detailAddress;
//@property (weak, nonatomic) IBOutlet UIButton *setDefaultAddress;
//@property (assign, nonatomic) BOOL ifSetDefalutAddress;

@property (strong, nonatomic) UIPickerView *myPicker;
@property (strong, nonatomic) UIView *pickerBgView;
//data
@property (strong, nonatomic) NSDictionary *pickerDic;
@property (strong, nonatomic) NSArray *provinceArray;
@property (strong, nonatomic) NSArray *cityArray;
@property (strong, nonatomic) NSArray *townArray;
@property (strong, nonatomic) NSArray *selectedArray;

@property (nonatomic,strong) UIButton *cancelButton;
@property (nonatomic,strong) UIButton *ensureButton;

@end

@implementation AddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.ifSetDefalutAddress = NO;
    self.title = self.titleName;
    self.address.delegate = self;
    self.phoneNumber.delegate = self;
    self.zipCode.delegate = self;
    [_phoneNumber addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_zipCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self getPickerData];
    //创建控件 picker
    [self createPikerAndAddressPickLable];
    [self textfieldStyle];
    if (!self.addressModel) {
        self.addressModel = [[AddressModel alloc] init];
    } else {
        self.name.text = _addressModel.name;
        self.phoneNumber.text = _addressModel.cellPhone;
        self.address.text = [NSString stringWithFormat:@"%@ %@ %@", _addressModel.province, _addressModel.city, _addressModel.district];
        self.zipCode.text = _addressModel.postCard;
        self.detailAddress.text = _addressModel.address;
    }
    if ([self.status isEqualToString:@"2"]) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStyleBordered target:self action:@selector(deleteAddressButton)];
    }
}

- (void)deleteAddressButton {
    [self requestData:YES];
}

- (void)textfieldStyle {
    self.name.layer.borderWidth = 1;
    self.name.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
    self.phoneNumber.layer.borderWidth = 1;
    self.phoneNumber.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
    self.address.layer.borderWidth = 1;
    self.address.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
    self.detailAddress.layer.borderWidth = 1;
    self.detailAddress.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
    self.zipCode.layer.borderWidth = 1;
    self.zipCode.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
    [UIUtil configTextField:_name withTitle:@""];
    [UIUtil configTextField:_phoneNumber withTitle:@""];
    [UIUtil configTextField:_zipCode withTitle:@""];
    [UIUtil configTextField:_address withTitle:@""];
}

- (void)requestData:(BOOL)ifDelete {
    self.addressModel.type = self.status;
    if (ifDelete) {
        self.addressModel.type = @"1";
    }
    self.addressModel.street = @"";
    self.addressModel.gender = @"男";
    NSDictionary *modelDic = self.addressModel.keyValues;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[UserModel sharedInstance].userName,@"userName",[UserModel sharedInstance].userToken,@"token", nil];
    [dic setValuesForKeysWithDictionary:modelDic];
    [RequestData updateAddress:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"提交失败":msg dismissBlock:nil];
            }
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg==nil?@"提交成功":msg dismissBlock:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - action methods
//- (IBAction)setDefalutAddress:(id)sender {
//    self.ifSetDefalutAddress = !self.ifSetDefalutAddress;
//    self.setDefaultAddress.selected = self.ifSetDefalutAddress;
//}

- (IBAction)submitButton:(id)sender {
    if ([self.name.text isEqualToString:@""] || [self.phoneNumber.text isEqualToString:@""] || [self.address.text isEqualToString:@""] || [self.detailAddress.text isEqualToString:@""] || [self.zipCode.text isEqualToString:@""]) {
        [[ESHUDView sharedInstance] showErrorMessage:@"姓名或手机号或地址不能为空" dismissBlock:nil];
        return;
    }
    self.addressModel.name = self.name.text;
    self.addressModel.cellPhone = self.phoneNumber.text;
    self.addressModel.postCard = self.zipCode.text;
    self.addressModel.address = self.detailAddress.text;
    self.addressModel.addressId = self.addressModel.addressId?self.addressModel.addressId:@"0";
    [self requestData:NO];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
    [self hideMyPicker];
}

#pragma mark 创建picker 接收数据label
- (void)createPikerAndAddressPickLable {
    self.pickerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, 320, 260)];
    [self.view addSubview:self.pickerBgView];
    self.pickerBgView.backgroundColor = [UIColor whiteColor];
    //我的picker
    self.myPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 240)];
    [self.pickerBgView addSubview:self.myPicker];
    self.myPicker.dataSource = self;
    self.myPicker.delegate = self;
    
    //取消button
    self.cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, self.myPicker.frame.size.height, SCREEN_WIDTH/2, 40)];
    [self.pickerBgView addSubview:self.cancelButton];
    [self.cancelButton addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    //    self.cancelButton.backgroundColor = [UIColor redColor];
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    self.cancelButton.layer.borderColor = [UIUtil colorWithHexString:@"#dddddd"].CGColor;
    self.cancelButton.layer.borderWidth = 1;
    [self.cancelButton setTitleColor:[UIUtil colorWithHexString:@"#787878"] forState:UIControlStateNormal];
    
    
    self.ensureButton = [[UIButton alloc] initWithFrame:CGRectMake(self.cancelButton.frame.origin.x+self.cancelButton.frame.size.width, self.cancelButton.frame.origin.y,  SCREEN_WIDTH/2, 40)];
    [self.pickerBgView addSubview:self.ensureButton];
    [self.ensureButton addTarget:self action:@selector(ensure:) forControlEvents:UIControlEventTouchUpInside];
    //    self.ensureButton.backgroundColor = [UIColor greenColor];
    [self.ensureButton setTitle:@"确定" forState:UIControlStateNormal];
    self.ensureButton.layer.borderColor = [UIUtil colorWithHexString:@"#dddddd"].CGColor;
    self.ensureButton.layer.borderWidth = 1;
    [self.ensureButton setTitleColor:[UIUtil colorWithHexString:@"#787878"] forState:UIControlStateNormal];
}

#pragma mark - get data
- (void)getPickerData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
    self.pickerDic = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.provinceArray = [self.pickerDic allKeys];
    self.selectedArray = [self.pickerDic objectForKey:[[self.pickerDic allKeys] objectAtIndex:0]];
    if (self.selectedArray.count > 0) {
        self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
    }
    if (self.cityArray.count > 0) {
        self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
    }
}

#pragma mark - UIPicker Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.provinceArray.count;
    } else if (component == 1) {
        return self.cityArray.count;
    } else {
        return self.townArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [self.provinceArray objectAtIndex:row];
    } else if (component == 1) {
        return [self.cityArray objectAtIndex:row];
    } else {
        return [self.townArray objectAtIndex:row];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return SCREEN_WIDTH/3;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.selectedArray = [self.pickerDic objectForKey:[self.provinceArray objectAtIndex:row]];
        if (self.selectedArray.count > 0) {
            self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
        } else {
            self.cityArray = nil;
        }
        if (self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
        } else {
            self.townArray = nil;
        }
    }
    [pickerView selectedRowInComponent:1];
    [pickerView reloadComponent:1];
    [pickerView selectedRowInComponent:2];
    if (component == 1) {
        if (self.selectedArray.count > 0 && self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:row]];
        } else {
            self.townArray = nil;
        }
        [pickerView selectRow:1 inComponent:2 animated:YES];
    }
    [pickerView reloadComponent:2];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 50;
}

#pragma mark - private method
- (void)showMyPicker {
    [self.view addSubview:self.pickerBgView];
//    self.maskView.alpha = 0;
    self.pickerBgView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, self.pickerBgView.frame.size.height);
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerBgView.frame = CGRectMake(0, self.view.frame.size.height - 260, SCREEN_WIDTH, self.pickerBgView.frame.size.height);
    }];
}

- (void)hideMyPicker {
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerBgView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, self.pickerBgView.frame.size.height);
    } completion:^(BOOL finished) {
        [self.pickerBgView removeFromSuperview];
    }];
}

#pragma mark -

- (void)cancel {
    [self hideMyPicker];
}

- (void)ensure:(id)sender {
    [self.address setText:[NSString stringWithFormat:@"%@ %@ %@",[self.provinceArray objectAtIndex:[self.myPicker selectedRowInComponent:0]],[self.cityArray objectAtIndex:[self.myPicker selectedRowInComponent:1]], [self.townArray objectAtIndex:[self.myPicker selectedRowInComponent:2]]]];
    self.addressModel.province = [self.provinceArray objectAtIndex:[self.myPicker selectedRowInComponent:0]];
    self.addressModel.city = [self.cityArray objectAtIndex:[self.myPicker selectedRowInComponent:1]];
    self.addressModel.district = [self.townArray objectAtIndex:[self.myPicker selectedRowInComponent:2]];
    [self hideMyPicker];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.address) {
        [self.zipCode endEditing:YES];
        [self showMyPicker];
        return NO;
    }
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField {
    if (textField == self.phoneNumber) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    if (textField == self.zipCode) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }
}

@end
